package ch1.vola;

import lombok.Data;

/**
 * 启动两个线程对count进行增长，如果是线程安全最后的值应该是两万
 */
@Data
public class NotSafe {
    private volatile long count = 0;
    private static Object object = new Object();

    public void count() {
        count++;
    }

    //定义一个线程
    private static class Count extends Thread {
        private NotSafe notSafe;

        public Count(NotSafe notSafe) {
            this.notSafe = notSafe;
        }

        @Override
        public void run() {
//            synchronized (object) {
                for (int i = 0; i < 10000; i++) {
                    notSafe.count();
                }
//            }
        }
    }

    //主线程
    public static void main(String[] args) throws InterruptedException {
        NotSafe notSafe = new NotSafe();
        //启动两个线程
        Count count1 = new Count(notSafe);
        Count count2 = new Count(notSafe);
        count1.start();
        count2.start();
        Thread.sleep(50);
        System.out.println(notSafe.count);
    }
}
